package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Map;

/**
 * @author Xxx
 */
@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ApUserSearchService userSearchService;

    /**
     * 文章搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        try {
            if (dto == null || dto.getMinBehotTime() == null) {
                return ResponseResult.okResult(null);
            }
            SearchRequest searchRequest = new SearchRequest("app_info_article");
            SearchSourceBuilder source = searchRequest.source();
            BoolQueryBuilder builder = new BoolQueryBuilder();
            if (dto.getSearchWords() == null) {
                builder.must(QueryBuilders.matchAllQuery());
            } else {
                userSearchService.insert(dto.getSearchWords());
                builder.must(QueryBuilders.matchQuery("title", dto.getSearchWords()));
            }
            builder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("title").preTags("<font style='color: red; font-size: inherit;'>").postTags("</font>");
            source.query(builder).from(dto.getFromIndex()).size(dto.getPageSize()).highlighter(highlightBuilder);
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHit[] hits = response.getHits().getHits();
            ArrayList<Map> list = new ArrayList<>();
            for (SearchHit hit : hits) {
                Map map = JSON.parseObject(hit.getSourceAsString(), Map.class);
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (!CollectionUtils.isEmpty(highlightFields)) {
                    Text title = highlightFields.get("title").getFragments()[0];
                    map.put("h_title", title.toString());
                } else {
                    map.put("h_title", map.get("title"));
                }
                list.add(map);
            }
            return ResponseResult.okResult(list);
        } catch (Exception e) {
            log.error("搜索失败!", e);
        }
        return ResponseResult.okResult(null);
    }
}
